package com.vichat.user.controller;

import com.alibaba.fastjson.JSON;
import com.vichat.common.util.AES;
import com.vichat.common.util.StringToPropertiesConverter;
import com.vichat.common.vo.Json;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.service.IUserService;
import com.vichat.user.vo.RequestParamsVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

/**
 * Created by wangluyin on 2018/6/6.
 */
@Controller
@RequestMapping("/vcapi/")
public class BaseController {
    private static Logger logger = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;


    @Autowired
    private IUserService userService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); // true:允许输入空值，false:不能为空值
    }


    /**
     * 根据access_token获取登陆用户信息
     *
     * @return
     */
    protected UserBasic getSessionUser() throws Exception {
        String uidStr = (String) request.getAttribute("uid");
        long uid = NumberUtils.toLong(uidStr);

        UserBasic sessionUser = userService.getUserBasicByUid(uid);
        if(sessionUser == null){
            throw new Exception("404");
        }
        return sessionUser;
    }

    protected void checkToken( RequestParamsVO paramsVO) throws Exception {

        String token = AES.decrypt(paramsVO.getToken());
        Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
        String uidInToken = properties.getProperty("uid");
        if (!StringUtils.equals(uidInToken, String.valueOf(paramsVO.getUid()))) {
            throw new Exception("token is illegal");
        }
    }

}
